<?php


namespace app\admin\service;


use app\admin\model\Admin;
use app\admin\model\AdminMenu;
use app\common\service\BaseService;
use app\common\service\TokenService;
use think\db\exception\DbException;
use think\facade\Db;
use think\facade\Request;

use function error_abort;
use function is_empty_parm;
use function now_time;

class AdminService extends BaseService
{
    public static function loginAdminUser($data) : array
    {
        $map[] = ['username', '=', $data['username']];
        $result = Admin::build()
                       ->where($map)
                       ->find();

        if (is_null($result)) {
            error_abort('账号不存在');
        }

        if ($result->getAttr('status') !== 1) {
            error_abort('账号已禁用');
        }
        if (!hash_equals($result->getAttr('password'), md6($data['password']))) {
            error_abort('账号或密码错误');
        }
        $data['last_login'] = now_time();
        $data['last_ip'] = Request::ip();
        unset($data['admin_id']);
        $result->allowField(['last_login', 'last_ip'])
               ->save($data);
        $result->admin_auths = AdminMenu::getListByGroup($result->group_id) ?? [];
        $adminId = $result->getAttr('admin_id');
        $tokenResult = TokenService::setToken($adminId, 1, $data['username'], $data['platform']);
        return ['admin' => $result->toArray(), 'token' => $tokenResult];
    }

    /**
     * @throws DbException
     */
    public static function getAdminList($extendQueryHelper, $data)
    {
        $query = Admin::build()
                            ->where($extendQueryHelper->where)
                            ->order($extendQueryHelper->sort, $extendQueryHelper->order);
        $map = [];
        !isset($data['admin_id']) ?: $map[] = ['admin_id', 'in', $data['admin_id']];
        empty($data['account']) ?: $map[] = ['username|nickname', '=', $data['account']];
        is_empty_parm($data['group_id']) ?: $map[] = ['group_id', '=', $data['group_id']];
        is_empty_parm($data['status']) ?: $map[] = ['status', '=', $data['status']];

        $query->keyWrod('admin_id|username|nickname|mobile', $data)
                    ->with(['authGroup'])
                    ->where($map);
        return $extendQueryHelper->is_page ? $query->_paginate() : $query->select();
    }

    public static function getAdminItem($admin_id) : Admin
    {
        return Admin::build()
                    ->with(['authGroup'])
                    ->findOrFail($admin_id);
    }

    public static function addAdminItem($data) : Admin
    {
        $model = new Admin();
        return Db::transaction(function () use ($data, $model)
        {
            $model->save($data);
            return $model->hidden(['password']);
        });
    }

    public static function setAdminItem($data) : Admin
    {
        $model = Admin::find($data['admin_id']);
        !$model && error_abort('当前管理员不存在!');
        return Db::transaction(function () use ($data, $model)
        {
            $model->save($data);
            return $model->hidden(['password']);
        });
    }

    public static function deleteAdminItem(int $admin_id) : bool
    {
        $admin = Admin::build()
                      ->findOrFail($admin_id);
        return $admin->delete();
    }

    public static function setPasswordByMobile($params)
    {
        $admin = Admin::build()
                      ->equal('mobile')
                      ->find();
        !$admin && error_abort('用户不存在!');
        $admin->password = $params['password'];
        return $admin->save();
    }




    public function setAdminPassword($old_password, $password, $password_confirm)
    {
        if ($password !== $password_confirm) {
            error_abort('确认密码不一致');
        }
        $admin = Admin::build()
                      ->find(get_client_id());
        if ($admin->password != md6($old_password)) {
            error_abort('原密码错误,请联系管理员!');
        }
        $admin->password = $password;
        $admin->save();
        return $admin;
    }

    /**
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws DbException
     */
    public function enable($admin_id)
    {
        $admin = Admin::build()
                      ->find($admin_id);
        $admin->status = 1;
        $admin->save();
        return $admin;
    }

    /**
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function disable($admin_id)
    {
        $admin = Admin::build()
                      ->findOrFail($admin_id);
        $admin->status = 0;
        $admin->save();
        return $admin;
    }

}